package com.zx.mes.upms.hyl.rest;

import com.zx.mes.hyl.common.msg.ObjectRestResponse;
import com.zx.mes.hyl.common.util.jwt.JWTHelper;
import com.zx.mes.upms.hyl.entity.User;
import com.zx.mes.upms.hyl.mapper.UserMapper;
import com.zx.mes.upms.hyl.pagemodel.UserInfo;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * JWT
 * @author hyl
 * @date 2017-12-17
 */

@RestController
@RequestMapping("jwt")
public class JWTController {

    private Integer expire;

    private String pubKeyPath;
    private String priKeyPath;

    private String namess;

    private Logger logger=Logger.getLogger(JWTController.class);

    @Autowired
    private JWTHelper jwtHelper;

    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/token")
    public ObjectRestResponse<UserInfo> authorize(String username, String password){
        logger.info("key:auth-123456789"+"用户名:"+username+" 密码:"+password);

        ObjectRestResponse<UserInfo> restResponse=new ObjectRestResponse<>();
        //1.校验帐户合法性
        User user=new User();
        User user2=new User();
        user.setUsername(username);
        user.setPassword(password);


        try {
            user2 = userMapper.selectOne(user);
            UserInfo userInfo=new UserInfo();
            userInfo.setUsername(user2.getUsername());
            userInfo.setName(user2.getUsername());
            userInfo.setUserId(user2.getId());
            //2.合法则生成token
            userInfo.setToken(jwtHelper.generateToken(userInfo,priKeyPath,expire));
            restResponse.setData(userInfo);
            restResponse.setRel(true);
            logger.info("key:auth-123456789"+"token:"+restResponse.getData());
            restResponse.setMessage("登录成功!");
        } catch (Exception e) {
            restResponse.setRel(false);
            restResponse.setStatus(500);
            restResponse.setMessage("异常:"+e.getMessage());
            e.printStackTrace();
        } finally {
        }

        return restResponse;
    }


    @RequestMapping("/logout")
    public ObjectRestResponse<String> logout(){
        return new ObjectRestResponse<>();
    }

    @GetMapping("/me")
    public ObjectRestResponse<Authentication> getCurrentAuthentication(Authentication authentication){
        return new ObjectRestResponse<>().rel(true).data(authentication);
    }
}
